import { defineComponent } from "@/shared/define.js";

class MyTabsController {
  /**
   * @type {string[]}
   */
  static $inject = ["$scope"];

  /**
   * @param {ng.IScope} $scope
   */
  constructor($scope) {
    this.$scope = $scope;
  }

  /**
   * @type {{selected: boolean}[]}
   */
  panes = [];

  /**
   * @param {{selected: boolean}} pane
   */
  select(pane) {
    for (const pane of this.panes) {
      pane.selected = false;
    }
    pane.selected = true;
  }

  /**
   * @param {{selected: boolean}} pane
   */
  addPane(pane) {
    if (this.panes.length === 0) {
      this.select(pane);
    }
    this.panes.push(pane);
  }

  handleClick() {
    console.log("MyTabsController", this);
  }
}

export const registerMyTabHtml = [
  "$templateCache",
  /**
   * @param {ng.ITemplateCacheService} $templateCache
   */
  ($templateCache) => {
    $templateCache.put(
      "my-tabs.html",
      /* HTML */ html`
        <div class="tabbable" aria-details="my-tabs-main">
          <ul class="nav nav-tabs">
            <li
              ng-repeat="pane in $tabCtrl.panes"
              ng-class="{active:pane.selected}"
            >
              <a href="" ng-click="$tabCtrl.select(pane)">{{pane.title}}</a>
            </li>
          </ul>
        </div>
        ${DebugButtonHTML("$tabCtrl")}
      `,
    );
  },
];

export const myTabs = defineComponent({
  transclude: true,
  controller: MyTabsController,
  controllerAs: "$tabCtrl",
  templateUrl: "my-tabs.html",
});

export const registerMyPaneHtml = [
  "$templateCache",
  /**
   * @param {ng.ITemplateCacheService} $templateCache
   */
  ($templateCache) => {
    $templateCache.put(
      "my-pane.html",
      /* HTML */ html`
        <div
          class="tab-pane"
          ng-show="$ctrl.selected"
          ng-transclude
          ng-click="$ctrl.handleClick()"
          aria-details="my-tabs-pane"
        ></div>
      `,
    );
  },
];

class MyPaneController {
  /**
   * @type {string[]}
   */
  static $inject = ["$scope"];

  /**
   * @param {ng.IScope} $scope
   */
  constructor($scope) {
    this.$scope = $scope;
  }

  $onInit() {
    // eslint-disable-next-line no-warning-comments
    // @ts-ignore - JS not have declare 😢
    this.tabsCtrl.addPane(this);
    console.log(this);
  }

  handleClick() {
    console.log("MyPaneController", this);
  }
}

export const myPane = defineComponent({
  transclude: true,
  require: {
    tabsCtrl: "^myTabs",
  },
  bindings: {
    title: "@",
  },
  controller: MyPaneController,
  templateUrl: "my-pane.html",
});
